<template>
  <el-dialog v-model="drawer" title="售后" width="700px" :append-to-body="true" custom-class="aftersaleDetail" :close-on-click-modal="true">
    <el-form size="small" ref="ruleRefForm" :model="params" :rules="rules" label-width="75px">
        <el-row :gutter="20" class="page-content">
            <el-col :span="24" style="margin-bottom: 10px;">
                <el-form-item label="订单号">{{form.orderSn || '-'}}</el-form-item>
            </el-col>
            <el-col :span="24" style="margin-bottom: 20px;">
                <el-form-item label="售后类型" prop="type">
                    <el-radio-group v-model="form.type" @change="selectReturnType">
                        <el-radio v-for="item in afterSaleList" :key="item.value" :label="item.value" size="small">{{item.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col v-if="form.type == 2 || form.type == 3" :span="24" style="margin-bottom: 20px;">
                <el-form-item label="收货人：" >
                    {{ shopInfo.receiveName }} - {{ form.receiverPhone }}
                </el-form-item>
                <el-form-item label="收货地址：" >
                    {{ shopInfo.receiveAddress }}
                </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-bottom: 20px;" v-if="(form.type == 1 || form.type == 3)">
            <!-- <el-col :span="24" style="margin-bottom: 20px;" v-if="(form.type == 1 || form.type == 3) && form.rootIn != 1 && form.rootIn != 2"> -->
                <el-form-item label="退款金额" prop="returnAmount">
                    <el-input-number v-model="params.returnAmount" :precision="2" :step="1" :min="0" :max="form.payAmount" />
                </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.type == 1 || form.type == 3">
                <el-form-item label="银行类型" prop="bankType">
                    <el-select v-model="params.bankType" placeholder="请选择" size="small" style="width: 252px;">
                        <el-option
                            v-for="item in bankList"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-bottom: 20px;" v-if="form.type == 1 || form.type == 3">
                <el-form-item label="收款账号" prop="bankCardSn">
                    <el-input v-model="params.bankCardSn" placeholder="请输入用户卡号" :minlength="16" :maxlength="19"  clearable @input="verifyCardNum" />
                </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 20px;">
                <el-table :data="form.orderItemList" size="small" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="产品图" prop="spuPic" width="120px" align="center">
                        <template #default="scope">
                            <img style="width: 30px; height: 30px" :src="scope.row.spuPic" fit="cover">
                        </template>
                    </el-table-column>
                    <el-table-column label="产品名称" prop="spuName" width="120px'"></el-table-column>
                    <el-table-column label="规格/详情" prop="skuName" width="140px"></el-table-column>
                    <el-table-column label="数量" prop="actualNum" align="center" width="60px">
                        <template #default="scope">
                            {{ verifySendNum(scope.row, 1) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="申请数量" prop="returnNum" align="center" >
                        <template #default="scope">
                            <el-input-number v-if="scope.row.actualNum > 0" v-model="scope.row.returnNum" :min="1" :max="scope.row.actualNum" size="small" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
            <el-col :span="24" style="margin-top: 20px;">
                <el-form-item label="原因" prop="reason">
                    <el-input type="textarea" placeholder="请输入" :rows="2" v-model="params.reason"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 20px;">
                <el-form-item label="上传凭证" prop="reason">
                    <el-upload v-model:file-list="files" ref="uploadBanner" :action="uploadUrl" :headers="headers"
                    list-type="picture-card" :auto-upload="true" :multiple="true" accept="image/*">
                        <el-icon>
                            <ele-Camera />
                        </el-icon>
                        <template #file="{ file }">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="图片" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon>
                                        <ele-ZoomIn />
                                    </el-icon>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <el-icon>
                                        <ele-Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-col>
            <el-col v-if="isApprevo == 1" :span="24" style="margin-top: 20px;">
                <el-form-item label="流程">
                    <el-timeline>
                        <el-timeline-item
                            v-for="(activity, index) in activities"
                            :key="index"
                            :timestamp="activity.timestamp"
                            >
                            {{ activity.content }}
                        </el-timeline-item>
                    </el-timeline>
                </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 20px;">
                <el-form-item label="执行人">
                    <div style="margin-top: 30px;">
                        <!-- <div v-for="(item, index) in params.executor" :key="index" style="display: flex; flex-direction: row; margin-bottom: 5px;">
                            <div v-if="item.userId == null || item == ''" class="none-icon" @click="selectExecutor(item.type)">
                                <i v-if="item.type == 0" class="fa fa-university" aria-hidden="true"></i>
                                <i v-if="item.type == 1" class="fa fa-jpy" aria-hidden="true"></i>
                            </div>
                            <div v-else class="executorLabel">
                                <el-tag closable @close="cancelSel(index)">{{ item.name }}</el-tag>
                            </div>
                        </div> -->
                        <div v-if="[2,3,4].includes(form.type)" style="margin-bottom: 10px; display: flex;">
                            <div style="width: 40px; margin-right: 10px;">仓库：</div>
                            <el-select v-model="warehouse" multiple class="m-2" placeholder="请选择执行人" @change="selectWarehouse">
                                <el-option v-for="item in warehouseUserList" :key="item.userId" :label="item.userName" :value="item.userId" />
                            </el-select>
                        </div>
                        <div v-if="form.type == 1 || form.type == 3" style="display: flex;">
                            <div style="width: 40px; margin-right: 10px;">钱：</div>
                            <el-select v-model="selectUsers" multiple class="m-2" placeholder="请选择执行人" @change="selectMoneyUser">
                                <el-option v-for="item in moneyUserList" :key="item.userId" :label="item.userName" :value="item.userId" />
                            </el-select>
                        </div>
                    </div>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    <template #footer>
        <el-row justify="center">
            <el-button size="small" type="primary" @click="submitForm(ruleRefForm)">提交</el-button>
            <el-button size="small" type="default" @click="cancelForm(ruleRefForm)">取消</el-button>
        </el-row>
    </template>

    <executor-list v-model:dialogDrawer="dialogExecutorVisible" v-model:type="selExecutorType" @onSubmit="callbackExecutor"></executor-list>
  </el-dialog>
</template>

<script>
import { computed, reactive, ref, toRefs, onMounted, nextTick } from 'vue'
import { useOrderApi } from '/@/api/order/index'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus'
import { verifiyNumberInteger } from '/@/utils/toolsValidate'
import { Session } from '/@/utils/storage'
import ExecutorList from '../components/ExecutorList.vue'

import api from '/@/api/commonApi'

export default {
    name: 'AfterSaleDetail',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        defaultForm: {
            type: Object,
            default(){
                return {}
            }
        }
    },
    components: {
        ExecutorList
    },
    setup(props, context){
        const { dialogDrawer, defaultForm } = toRefs(props)
        const orderApi = useOrderApi()
        const storeUserInfo = useUserInfo() // 订单各类状态数据
        const { userInfos } = storeToRefs(storeUserInfo)
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        const form = computed({
            get: () => {
                defaultForm.value.orderItemList.forEach(item => {
                    if(defaultForm.value.returnList.length > 0) {
                        let returnData = defaultForm.value.returnList.find(val => {
                            return val.skuId == item.skuId
                        })
                        if(returnData != null) {
                            item.returnNum =item.actualNum > 0 ? item.actualNum - returnData.skuCount : 0
                        }else{
                            item.returnNum = item.actualNum > 0 ? item.actualNum : 0
                        }
                    }else{
                        item.returnNum = item.actualNum > 0 ? item.actualNum : 0
                    }
                })
                salesReturnAddress(defaultForm.value.managerId)
                defaultForm.value.type = 1
                return defaultForm.value
            },
            set: val => {
                context.emit('update:defaultForm', val)
            }
        })
        const ruleRefForm = ref()
        const state = reactive({
            uploadUrl: '/api/file/filaAttach/upload',
            headers: {
                '17work': Session.get('token')
            },
            files: [], // 凭证
            form: {
                type: 1,
                operateMan: userInfos.value.id
            },
            rules: {
                type: [{ required: true, message: '请选择售后类型', trigger: 'blur' }],
                bankType: [{ required: true, message: '请选择银行类型', trigger: 'blur' }],
                bankCardSn: [{ required: true, message: '请输入收款账号', trigger: 'blur' }]
            },
            afterSaleList: [{
                label: '退款',
                value: 1
            },{
                label: '退货',
                value: 2
            },{
                label: '退货退款',
                value: 3
            },{
                label: '重发补发',
                value: 4
            }],
            deliveryList: [],
            returnMoney: 0, // 退款金额
            bankList: [], // 银行列表
            params: {
                orderId: '', // 订单id
                orderSn: '', // 订单号
                sourceType: 1, // 来源
                memberUsername: '', // 会员昵称
                returnAmount: 0, // 退款金额
                returnName: '', // 退货人姓名
                returnPhone: '', // 退货人电话
                reason: '', // 原因
                description: '', //描述
                productList: [], // 申请商品
                bankType: '', // 银行
                type: 1, // 售后类型
                bankCardSn: '', //收款账号
                descPics: '', // 凭证图片
                executor: [ // 执行人
                    // {
                    //     type: 0, // 仓库
                    //     name: '',
                    //     userId: null
                    // },
                    // {
                    //     type: 1, // 钱
                    //     name: '',
                    //     userId: null
                    // }
                ],
            },
            shopInfo: {}, // 店铺信息
            isApprevo: 0, // 不需要审批
            activities: [ // 审批流程
                {
                    content: '审批人',
                    timestamp: '张三',
                },
                {
                    content: '抄送人',
                    timestamp: '王麻子',
                },
            ], 
            selExecutorType: 0, // 选择执行人类型
            dialogExecutorVisible: false, // 执行人列表控制
            warehouseUserList: [], // 仓库执行人
            moneyUserList: [], // 钱执行人
            warehouse: [], // 选择的仓库执行人
            selectUsers: [], // 选择钱的执行人
        })
        const close = () => {
            reset()
            context.emit('update:dialogDrawer', false)
        }
        const submitForm = (formEl) => {
            if (!formEl) return
            formEl.validate((valid) => {
                if (valid) {
                    state.params.executor = []
                    state.params.orderId = form.value.id
                    state.params.orderSn = form.value.orderSn
                    state.params.returnCustomerId = form.value.customerId
                    state.params.returnUsername = form.value.customerName
                    state.params.memberUsername = form.value.memberUsername
                    state.params.returnName = form.value.receiverName
                    state.params.returnPhone = form.value.receiverPhone
                    state.params.type = form.value.type
                    state.params.returnAmount = form.value.type == 2 || form.value.type == 4 ? 0 : state.params.returnAmount
                    if (state.files.length > 0) {
                        let params = []
                        state.files.forEach(item => {
                            params.push(item.response.data.src)
                        })
                        state.params.descPics = params.join(",")
                    }
                    if (state.warehouse.length > 0) {
                        state.warehouseUserList.forEach(item => {
                            if(state.warehouse.includes(item.userId)) {
                                state.params.executor.push({
                                    type: 0,
                                    userId: item.userId,
                                    name: item.userName
                                })
                            }
                        })
                    }
                    if (state.selectUsers.length > 0) {
                        state.moneyUserList.forEach(item => {
                            if(state.selectUsers.includes(item.userId)) {
                                state.params.executor.push({
                                    type: 1,
                                    userId: item.userId,
                                    name: item.userName
                                })
                            }
                        })
                    }
                    console.log(state.params);
                    if (state.params.returnAmount < 0.01 && (state.params.type == 1 || state.params.type == 3)) {
                        return ElMessage.warning("退款金额不能为0")
                    }else if(state.params.productList.length == 0 && state.params.type != 1) {
                        return ElMessage.warning("请选择商品")
                    }else {
                        api.addReturnApply(state.params).then(res => {
                            ElMessage.success("提交售后申请成功")
                            context.emit('onSubmit', true) // 提交
                            context.emit('update:dialogDrawer', false)
                        })
                    }
                }
            })
        }
        const cancelForm = formEl => {
            if (!formEl) return
            formEl.resetFields()
            context.emit('update:dialogDrawer', false)
        }
        // 选择退货的商品
        const handleSelectionChange = (val) => {
            state.params.productList = []
            if (val.length > 0) {
                val.forEach(item => {
                    state.params.productList.push({
                        orderId: item.orderId,
                        orderItemId: item.id,
                        spuId: item.spuId,
                        spuName: item.spuName,
                        skuId: item.skuId,
                        skuName: item.skuName,
                        skuImg: item.spuPic,
                        skuPrice: item.skuPrice,
                        skuRealPrice: item.skuPrice,
                        number: item.returnNum
                    })
                })
            }
        }
        // 已发数量
        const verifySendNum = (item, type) => {
            if (type == 1) {
                return item.actualNum
            }else {
                return item.needNum
            }
        }
        // 选择售后类型
        const selectReturnType = (e) => {
            console.log(e);
            if (e == 1) {
                nextTick(() => {
                    state.rules = {
                        type: [{ required: true, message: '请选择售后类型', trigger: 'blur' }],
                        bankType: [{ required: true, message: '请选择银行类型', trigger: 'blur' }],
                        bankCardSn: [{ required: true, message: '请输入收款账号', trigger: 'blur' }]
                    }
                    state.params.executor = [
                        // {
                        //     type: 1, // 钱
                        //     name: '',
                        //     userId: null
                        // }
                    ]
                })
            }else if(e == 3) {
                nextTick(() => {
                    state.rules = {
                        type: [{ required: true, message: '请选择售后类型', trigger: 'blur' }],
                        bankType: [{ required: true, message: '请选择银行类型', trigger: 'blur' }],
                        bankCardSn: [{ required: true, message: '请输入收款账号', trigger: 'blur' }],
                        productList: [{ required: true, message: '请选择退货商品', trigger: 'blur' }]
                    }
                    state.params.executor = [
                        // {
                        //     type: 0, // 仓库
                        //     name: '',
                        //     userId: null
                        // },
                        // {
                        //     type: 1, // 钱
                        //     name: '',
                        //     userId: null
                        // }
                    ]                    
                })
            }else {
                nextTick(() => {
                    state.rules = {
                        type: [{ required: true, message: '请选择售后类型', trigger: 'blur' }],
                        productList: [{ required: true, message: '请选择退货商品', trigger: 'blur' }],
                    }       
                    state.params.executor = [
                        // {
                        //     type: 0, // 仓库
                        //     name: '',
                        //     userId: null
                        // }
                    ]             
                })
            }
        }
        // 获取银行
        const bankTypeList = () => {
            api.allDictLists().then(res => {
                state.bankList = res.data['BankType']
            })
        }
        // 校验银行卡号
        const verifyCardNum = (e) => {
            state.params.bankCardSn = verifiyNumberInteger(e)
        }
        // 店铺信息
        const salesReturnAddress = (e) => {
            api.salesReturnAddress({enterpriseId: e}).then(res => {
                state.shopInfo = res.data
            })
        }
        // 重置数据
        const reset = () => {
            state.params = {
                orderId: '', // 订单id
                orderSn: '', // 订单号
                memberUsername: '', // 会员昵称
                returnAmount: 0, // 退款金额
                returnName: '', // 退货人姓名
                returnPhone: '', // 退货人电话
                reason: '', // 原因
                description: '', //描述
                productList: [], // 申请商品
                bankType: '', // 银行
                type: 1, // 售后类型
                bankCardSn: '', //收款账号
                descPics: '', // 凭证图片
                executor: [ // 执行人
                    // {
                    //     type: 0, // 仓库
                    //     url: '',
                    //     name: '',
                    //     userId: null
                    // },
                    // {
                    //     type: 1, // 钱
                    //     url: '',
                    //     name: '',
                    //     userId: null
                    // }
                ],
            }
        }
        const handlePictureCardPreview = (file) => {
            state.dialogImageUrl = file.url
            state.dialogBannerVisible = true
        }
        const handleRemove = file => {
            uploadBanner.value.handleRemove(file)
        }
        // 选择执行人弹窗
        const selectExecutor = (type) => {
            state.selExecutorType = type
            state.dialogExecutorVisible = true
        }
        // 执行人数据
        const callbackExecutor = (val) => {
            console.log(val);
            state.params.executor.forEach(item => {
                if(item.type == state.selExecutorType){
                    nextTick(() => {
                        item.userId = val.userId
                        item.name = val.userName
                    })
                }
            })
            console.log(state.params.executor);
        }
        // 取消执行人
        const cancelSel = (index) => {
            state.params.executor[index].userId = null
            state.params.executor[index].name = ''
        }
        // 获取售后是否需要审批
        const alfterSaleApprevo = () => {
            api.matterIsApprove({code: 'AFTER_SALE'}).then(res => {
                if (res.data == 1) {
                    // TODO 获取审批人流程
                }
                state.isApprevo = res.data
            })
        }
        // 获取执行人列表
        const getExecutorList = (type) => {
            api.moneyExecutorList({code: 'payable'}).then(res => {
                state.moneyUserList = res.data
            })
            api.libExecutorList({code: 'afterSaleList'}).then(res => {
                state.warehouseUserList = res.data
                res.data.forEach(item => {
                    state.warehouse.push(item.userId)
                })
            })
        }
        // 选择仓库人员
        const selectWarehouse = (val) => {
            console.log(val);
        }
        // 选择钱人员
        const selectMoneyUser = (val) => {
            console.log(val);
        }

        onMounted(() => {
            bankTypeList()
            alfterSaleApprevo()
            getExecutorList()
        })
        return {
            ...toRefs(state),
            onMounted,
            drawer,
            form,
            close,
            reset,
            cancelSel,
            ruleRefForm,
            submitForm,
            cancelForm,
            bankTypeList,
            verifyCardNum,
            verifySendNum,
            selectWarehouse,
            selectMoneyUser,
            selectReturnType,
            salesReturnAddress,
            handlePictureCardPreview,
            handleRemove,
            selectExecutor,
            callbackExecutor,
            alfterSaleApprevo,
            handleSelectionChange,
        }
    }
}
</script>

<style>
.none-icon {
    width: 30px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    border: 1px solid #dcdfe6;
}

.executorLabel {
    width: auto;
    height: 30px;
    color: #FFFFFF;
    /* background: #409EFF; */
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    /* padding: 0 10px; */
    border-radius: 5px;
}
</style>